<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../data-jelly-fish/css/layui.css">
</head>
<body  style="margin:20px;">
    <form class="layui-form" action="" lay-filter="example">
        <div class="layui-form-item">
            <label class="layui-form-label">名称</label>
            <div class="layui-input-block">
                <input type="text" name="name" lay-verify="title" autocomplete="off" placeholder="请输入名称" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">来源地址</label>
            <div class="layui-input-block">
                <input type="text" name="url" lay-verify="title" autocomplete="off" placeholder="请输入远程地址" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">告警地址</label>
            <div class="layui-input-block">
                <input type="text" name="warningUrl" lay-verify="title" autocomplete="off" placeholder="请输入告警地址" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">频次(秒)</label>
            <div class="layui-input-block">
                <input type="text" name="delay" lay-verify="title" autocomplete="off" value="" placeholder="请输入频次" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">偏移量字段(offset)</label>
            <div class="layui-input-block">
                <input type="text" name="offsetFields.offset" lay-verify="title" autocomplete="off" value="" placeholder="（非空字段）" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">主键字段(uId)</label>
            <div class="layui-input-block">
                <input type="text" name="offsetFields.uId" lay-verify="title" autocomplete="off" value="" placeholder="（非空字段）" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">启用</label>
            <div class="layui-input-block">
                <input type="checkbox" checked=""  name="status" lay-skin="switch" lay-text="ON|OFF" >
            </div>
        </div>
        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
            <legend style="font-size: 15px;font-weight: bold">任务分片，至少1个</legend>
        </fieldset>
        <table class="layui-table" id="test" lay-filter="test"></table>
        <button type="button" onclick="shardingAdd()" class="layui-btn">添加</button>
        <fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
        </fieldset>
        <div style="text-align: right;">
            <button type="button" id="saveTopIcBtn" onclick="saveTopIc()" style="display: none" class="layui-btn layui-btn-normal">保存</button>
            <button type="button" id="nextConsumerBtn" onclick="nextConsumer()" style="display: none"  class="layui-btn layui-btn-normal">下一步</button>
        </div>
    </form>

<script src="../data-jelly-fish/layui.js"></script>
<script>

    var $ ;
    var table  = null;
    var form;
    var layer;
    layui.use('form', function(){
        form = layui.form;
        layer = layui.layer;
    });
    layui.use('table', function(){
         table = layui.table;
         $ = layui.jquery;

         init();

        table.render({
            elem: '#test'
            ,cellMinWidth: 80
            ,data:[
                {
                    "key":"shard1",
                    "offset":"",
                    "uId":"",
                    "filter":'{}'
                }
            ]
            ,cols: [
                [
                    {field:'key',  title: 'key',edit: 'text'}
                    ,{field:'offset',  title: 'offset',edit: 'text'}
                    ,{field:'uId',  title: 'uId',edit: 'text'}
                    ,{field:'filter', width:500, title: 'filter',edit: 'json'}
                    ,{fixed: 'right', width:178, align:'center', toolbar: '#barDemo',  title: '操作'}
                ]
            ]
        });


        table.on('tool(test)', function (obj) {
            if(obj.event === "del"){
                var oldData = table.cache["test"];
                oldData.splice(obj.tr.data('index'),1);
                layer.msg("删除成功",{time: 500},function(){
                    table.reload('test',{data : oldData});
                });
            }
        });

    });

    var id ;

    function init(){
        id = getUrlParam().id;

        if (id){
            $("#saveTopIcBtn").show();
        }else{
            $("#nextConsumerBtn").show();
        }

        //表单赋值
        if (id){
            $.get("../topic/"+id,function (data) {
                if(!data.data){
                    return;
                }
                data.data['offsetFields.offset'] = data.data.offsetFields.offset;
                data.data['offsetFields.uId'] = data.data.offsetFields.uId;
                form.val('example', data.data);
                table.reload('test', {data: data.data.shardings});
            })
        }
    }

    function shardingAdd() {
        var tabledata = table.cache["test"];

        var key = "shard1";
        if (tabledata.length>0){
            var lastData = tabledata[tabledata.length-1];
            var suffixNum = lastData.key.match(/\d*$/)[0];
            if (suffixNum){
                var prefix = lastData.key.replace(/\d*$/,"");
                key = prefix + (parseInt(suffixNum)+1);
            }
        }

        tabledata.push({
            "key":key,
            "offset":"",
            "uId":"",
            "filter":"{}"
        })
        table.reload('test', {data: tabledata});
    }

    function getUrlParam() {
        let query = window.location.search.substring(1);
        let vars = query.split("&");
        let urlParam = {};
        for (let i=0;i<vars.length;i++) {
            let pair = vars[i].split("=");
            urlParam[pair[0]] = pair[1];
        }
        return urlParam;
    }

    var id = getUrlParam().id;

    function saveTopIc(next) {
        var formData = form.val('example');
        var data = {
            "id":id,
            "name":formData.name,
            "url":formData.url,
            "warningUrl":formData.warningUrl,
            "delay":formData.delay,
            "offsetFields":{
                "offset":formData['offsetFields.offset'],
                "uId":formData['offsetFields.uId']
            },
            "status":formData.status == "on"?1:0,
            "shardings": table.cache["test"]
        }

        $.ajax({
            type: "POST",
            url: "../topic",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(data),
            dataType: "json",
            success: function (message) {
                if (message.code == 0){
                    layer.msg('保存成功',{time: 500});
                    var index = parent.layer.getFrameIndex(window.name);
                    parent.layer.close(index);
                    parent.layui.table.reload('test');
                    if (next){
                        next(message.data);
                    }
                }else{
                    layer.msg('保存异常',{time: 500});
                }
            }
        });

    }

    function nextConsumer() {
        saveTopIc(function (topicId) {
            parent.showAddCustomer(topicId);
        });
    }
</script>
<script type="text/html" id="barDemo">
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>

    <style type="text/css">
        .layui-form-label{
            width:170px;
        }
        .layui-input-block{
            margin-left:200px;
        }
    </style>
</body>
</html>
